package cn.yunyichina.provider.guide.service.impl;

import java.util.Calendar;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import cn.yunyichina.provider.guide.GuideConstants;
import cn.yunyichina.provider.guide.dao.InstanceDao;
import cn.yunyichina.provider.iface.entity.ErrorCodeDefine;

/**
 * 导医,定时结束导医流程
 * 
 * @author adriftor
 *
 */
@Service("guidesyncstopServiceImpl")
public class GuideSyncStopServiceImpl {

	private static final Logger logger = LoggerFactory.getLogger(GuideSyncStopServiceImpl.class);

	@Resource
	private InstanceDao instanceDao;

	private static Boolean isRunning = false;

	private static Long lastSchEndTime = System.currentTimeMillis();

	/**
	 * 定时结束导医流程
	 */
	public void schEndInstance() {
		if (isRunning) {
			logger.info("定时结束导医流程正在运行,禁止重入");
			return;
		}

		isRunning = true;

		try {
			/**
			 * 一小时新一次，更新时间为晚上10点一会后，早上6点之前
			 */
			Long start = System.currentTimeMillis();
			if ((start - lastSchEndTime) / 1000 > 3600) {

				logger.info("schEndInstance--start");
				Calendar c = Calendar.getInstance();
				int hour = c.get(Calendar.HOUR_OF_DAY);
				if (hour>=22 || hour <=6) {
					logger.info("结束过期的导医流程");
					c.add(Calendar.DATE, -1);
					instanceDao.schEndInstances(GuideConstants.YYYYMMDDHHMMSS.format(c.getTime()));
					lastSchEndTime = System.currentTimeMillis();
				}
				
				logger.info("schEndInstance--ok");

			}

		}
		catch (Exception ex) {
			logger.error(ErrorCodeDefine.GUIDE_COMMON, "定时结束导医流程异常", ex);
		} finally {
			isRunning = false;
		}
	}

}
